
var Inventory = {

    validateShortName : function(){
       var value = $.trim($("#shortName").val());
       ValidationUtil.clearErrorMsg("shortName");
       if(ValidationUtil.isBlank(value)){
            ValidationUtil.showErrorMsg("shortName", "isEmpty");
            return false;
       }
       if(value.bLength()>20){
            ValidationUtil.showErrorMsg("shortName", "stringLengthTooLong","","20");
            return false;
       }
       return true;
    },

    validateFullName : function(){
       var value = $.trim($("#fullName").val());
       ValidationUtil.clearErrorMsg("fullName");
       if(ValidationUtil.isBlank(value)){
            ValidationUtil.showErrorMsg("fullName", "isEmpty");
            return false;
       }
       if(value.bLength()>100){
            ValidationUtil.showErrorMsg("fullName", "stringLengthTooLong","","100");
            return false;
       }
       return true;
    },

    validateUrlTitle : function(){
       var value = $.trim($("#urlTitle").val());
       ValidationUtil.clearErrorMsg("urlTitle");
       if(ValidationUtil.isBlank(value)){
            ValidationUtil.showErrorMsg("urlTitle", "isEmpty");
            return false;
       }
       return true;
    },

    validateParentCategory : function(){
        var selectId = tree.getAllChecked();
        ValidationUtil.clearErrorMsg("parent");
        if(selectId == ""){
            ValidationUtil.showErrorMsg("parent", "isEmpty");
            return false;
        }
        return true;
    },

    copyShortName : function(){
        var shortName = $("#shortName").val();
        $("#fullName").val(shortName);
        shortName = shortName.replace(/ /ig, "-");
        $("#urlTitle").val(shortName.toLowerCase());
        $("#urlTitleMsgLabel").html(shortName.toLowerCase());
    },
    
    addCategory : function(baseUrl){
         var result = true;
         if(!this.validateShortName()){
             result = false;
         }
         if(!this.validateFullName()){
             result = false;
         }
         if(!this.validateUrlTitle()){
             result = false;
         }
         if(!this.validateParentCategory()){
             result = false;
         }
         if(!result){
            return;
         }
         var url = baseUrl + "/inventory/category/subadd";
         var selectId = tree.getAllChecked();
         $("#parent").val(selectId);
         var data = $("#addCategory").serialize();
         $.ajax({
            type:"POST",
            async:false,
            url:url,
            data: data,
            dataType:"Html",
            success:function(responseText){
                if(responseText != "true"){
                    $("#categoryDialog").empty();
                    $("#categoryDialog").html(responseText);
                }else{
                    window.location = baseUrl + "/inventory/category";
                }              
            }
         });
    },

    subEditCategory : function(baseUrl){
         var result = true;
         if(!this.validateShortName()){
             result = false;
         }
         if(!this.validateFullName()){
             result = false;
         }
         if(!this.validateUrlTitle()){
             result = false;
         }
         if(!this.validateParentCategory()){
             result = false;
         }
         if(!result){
            return;
         }
         var url = baseUrl + "/inventory/category/subedit";
         var selectId = tree.getAllChecked();
         $("#parent").val(selectId);
         var data = $("#addCategory").serialize();
         $.ajax({
            type:"POST",
            async:false,
            url:url,
            data: data,
            dataType:"Html",
            success:function(responseText){
                if(responseText != "true"){
                    $("#categoryDialog").empty();
                    $("#categoryDialog").html(responseText);
                }else{
                    window.location = baseUrl + "/inventory/category";
                }
            }
         });
    },
    
    selectCheckBox : function(eventId){
        var selectId = tree.getAllChecked();
        if(selectId && selectId != ""){
            var ids = selectId.split(",");
            for(i=0 ; i< ids.length ; i++){
                 tree.setCheck(ids[i], 0)
            }
        }
        tree.setCheck(eventId, 1);
    },

    initCategoryTree : function(treeId,categoryXml,imagePath,checkStatus){
         var tree=new dhtmlXTreeObject(treeId,"100%","100%",0);
         tree.setImagePath(imagePath);
         tree.enableCheckBoxes(checkStatus);
         tree.enableTreeImages(0);
         tree.enableThreeStateCheckboxes(0);
         tree.loadXMLString(categoryXml);
         return tree;
    },

    editCategory : function(){
        var selectId = tree.getAllChecked();
        if(selectId && $.trim(selectId) != ""){
            if(selectId != '-1'){
                Common.gotoUrl(url + "/inventory/category/edit/id/" + selectId);
            }else{
                alert("You can't edit 'Root'");
            }
        }else{
            alert("Please select a category.");
        }
    },

    clickCategory : function(eventId){
        if(eventId != '-1'){
            //Common.gotoUrl(url + "/inventory/category/edit/id/" + eventId);
//            Common.showDialog({
//                url : url + "/inventory/category/edit/id/" + eventId ,
//                height : 580 ,
//                width : 750 ,
//                dataDiv : "categoryDialog"
//            });
              $("#categoryEventId").val(eventId);
              $("#categoryConfirmDialog").dialog({
                            modal: true ,
                            height: 100 ,
                            autoOpen: false,
                            width: 180,
                            resizable: false,
                            overlay: {
                               opacity: 0.6,
                               background: "#555555"
                            },
                            close: function(event, ui) {
                                $("#categoryConfirmDialog").dialog('destroy');
                            }
              });
              $("#categoryConfirmDialog").dialog("open");
        }else{
            jAlert("You can't edit 'Root'");
        }
    },
    
    deleteCategory : function(){
        var selectId = tree.getAllChecked();
        if(selectId && $.trim(selectId) != ""){
            if(selectId != '-1'){
                if(confirm('Are you sure you want to do this?')){
                    Common.gotoUrl(url + "/inventory/category/delete/id/" + selectId);
                }
            }else{
                alert("You can't delete 'Root'");
            }
        }else{
            alert("Please select a category.");
        }
    },

    addAttributeValue : function(index){
        var value = $.trim($("#valueBox" + index).val());
        var text = $.trim($("#valueBox" + index).val());
        if($("#valueBox" + index).attr('selectedIndex') || $("#valueBox" + index).attr('selectedIndex') == 0){
           var selectedIndex = $("#valueBox" + index).attr('selectedIndex');
           text = $.trim($("#valueBox" + index + "Option" + selectedIndex).text());
        }
        if(value != ""){
            var result = true;
            $("#valueSelect" + index + " option").each(function(){
               if($(this).val() == value){
            	    alert("该属性值与'"+ $(this).text() +"'相同,若想添加请先删除'"+ $(this).text() +"'");
                    result = false;
               }
            });
            if(result){
                var option = "<option value='"+ value +"'>";
                option += text;
                option += "</option>";
                $(option).appendTo("#valueSelect" + index);
            }
        }
        $("#valueBox" + index).val("");
    },

    removeAttributeValue : function(index){
          $("#valueSelect" + index + " option").each(function(){
               if($(this).attr("selected")){
                    $(this).remove();
               }
          });
    },

    submitAttributeForm: function(){
          var i = 1;          
          for(i;i<6;i++){
              var valueArr = new Array();
              $("#valueSelect" + i + " option").each(function(){
                   var value = $(this).val();
                   if(value != ""){
                       valueArr.push(value);
                   }
              });
              $("#value" + i).val(valueArr.join());
          }
          $("form").submit();
    },

    openAttrDialog: function(){
        $("#addAttrDialog").dialog({
                                modal: true ,
                                height: 600 ,
                                autoOpen: false,
                                width: 780,
                                resizable: false,
                                overlay: {
                                   opacity: 0.6,
                                   background: "#555555"
                                }
         });
        $("#addAttrDialog").dialog("open");
    },

    closeAttrDialog: function(){
        $("#addAttrDialog").dialog("close");
    },

    validateMetadataValue : function(i){
        var valueSelect = document.getElementById("valueSelect"+i);
        if(valueSelect){
            $("#valueSelect"+i).css("border","1px solid black");
            ValidationUtil.clearErrorMsg("metedataValue"+i);
            var valueCount = $("#valueSelect" + i + " option").size();
            if(valueCount == 0){
                ValidationUtil.showErrorMsg("metedataValue"+i, "isEmpty");
                $("#valueSelect"+i).css("border","1px solid red");
                return false;
            }
        }
        return true;
    },

    initAttributes: function(){
          var result = true;
          if(!this.validateMetadataValue("1")){
              result = false;
          }
          if(!this.validateMetadataValue("2")){
              result = false;
          }
          if(!this.validateMetadataValue("3")){
              result = false;
          }
          if(!this.validateMetadataValue("4")){
              result = false;
          }
          if(!this.validateMetadataValue("5")){
              result = false;
          }
          if(!result){
            return;
          }
          var attributes = new Array();
          var names = new Array();
          var items = new Array();
          var labels = new Array();
          var num = 1;
          for(i=1;i<6;i++){
                var name = $.trim($("#attribute" + i).val());
                valueCount = $("#valueSelect" + i + " option").size();
                if(name != "" && valueCount != 0){
                    var attribute = {"index" : i-1 , "value" : $("#valueSelect" + i + " option")};
                    num *= valueCount;
                    attributes.push(attribute);
                    names.push(name);
                }
          }
          repeatNum = num;
          $(attributes).each(function(n,obj1){
              valueList = obj1.value;
              index = obj1.index;
              valueListCount = $(valueList).size();
              repeatNum = repeatNum / valueListCount;
              k = 1;
              $(valueList).each(function(n,obj2){
                    startPoint = k;
                    spaceCount = num / valueListCount / repeatNum;
                    for(j=1; j<=spaceCount; j++){
                        for(i=0; i<repeatNum; i++){
                            if(!items[startPoint+i-1]){
                                items[startPoint+i-1] = new Array();
                                labels[startPoint+i-1] = new Array();
                            }
                            items[startPoint+i-1][index] = $.trim($(obj2).val());
                            labels[startPoint+i-1][index] = $.trim($(obj2).text());
                        }
                        startPoint += repeatNum * valueListCount;
                    }
                    k += repeatNum;
              });
          });
          this.initAttributeTables(names, items , labels);
    },

    initAttributeTables: function(names,items,labels){
        if(items.length == 0){
            this.closeAttrDialog();
            return;
        }
        var purchasingPricePreset = $("#purchasingPricePreset").val();
        var costPricePreset = $("#costPricePreset").val();
        var marketingPricePreset = $("#marketingPricePreset").val();
        var listPricePreset = $("#listPricePreset").val();
        var salePricePreset = $("#salePricePreset").val();
        var weightPreset = $("#weightPreset").val();
        var inventoryPreset = $("#inventoryPreset").val();
        var table = "";
        table += "<input type='hidden' id='attributeCount' value='" + items.length + "' />";
        table += "<div style='margin-left:15px;'>";
        table += '<input type="button" value="重新生成子产品" onclick="javascript:Inventory.modifyItems();" />';
        table += '<input type="button" value="删除子产品" onclick="javascript:Inventory.removeAttributes();" />';
        table += '<input type="button" value="添加子产品" onclick="javascript:Inventory.addAttribute('+ names.length +');" />';
        table += "</div>";
        //table += "<div class='clear'></div>";
        table += '<div style="margin-left:20px;margin-top:5px;">';
        table += '<div id="itemErrorError" class="form_element_error"></div>';
        table += '</div>';
        //table += "<div class='clear'></div>";
        table += '<table cellspacing="0" cellpadding="0" style="text-align:left;">';
        table += '<thead>';
        table += '<tr>';
        table += "<td class='dbgrid_th_ckb' style='cursor:default;'><span>&nbsp;</span></td>";
        table += "<td class='dbgrid_th' style='cursor:default;'><span>ID</span></td>";
        table += "<td class='dbgrid_th' style='cursor:default;'><span>UPC</span></td>";
        for(i=0;i<names.length;i++){
            //table += "<td class='dbgrid_th' style='cursor:default;'><span>Attribute"+ i +"</span></td>";
            table += "<td class='dbgrid_th' style='cursor:default;'><span>" + names[i] + "<input type='hidden' name='attribute[]' value='"+ names[i] +"' size='10' class='attribute_input_text' /></span></td>";
        }       
        //table += "<td class='dbgrid_th' style='cursor:default;'><span>SKU</span></td>";
        table += "<td class='dbgrid_th' style='cursor:default;'><span>进货价</span></td>";
        table += "<td class='dbgrid_th' style='cursor:default;'><span>成本价</span></td>";
        table += "<td class='dbgrid_th' style='cursor:default;'><span>市场价</span></td>";
        table += "<td class='dbgrid_th' style='cursor:default;'><span>米米价</span></td>";
        table += "<td class='dbgrid_th' style='cursor:default;'><span>售价</span></td>";
        table += "<td class='dbgrid_th' style='cursor:default;'><span>重量</span></td>";
        table += "<td class='dbgrid_th' style='cursor:default;'><span>库存</span></td>";
        //table += "<td class='dbgrid_th' style='cursor:default;'><span>Place</span></td>";
        //table += "<td class='dbgrid_th' style='cursor:default;'><span>Shipping Type</span></td>";
        //table += "<td class='dbgrid_th' style='cursor:default;'><span>Can Free Shipping</span></td>";
        table += "<td class='dbgrid_th' style='cursor:default;'><span>是否显示</span></td>";
        table += "<td class='dbgrid_th' style='cursor:default;'><span>默认子产品</span></td>";
        table += "</tr>";
        table += "</thead>";
        table += '<tbody id="attributeTableTbody">';
        for(i=0;i<items.length;i++){
            table += "<tr id='attributeRow"+ i +"'>";
            table += "<td class='dbgrid_td_ckb'><input type='hidden' name='itemId[]' value='0' /><input type='checkbox' name='attributeCheckBox' value='"+ i +"' /></td>";
            table += "<td class='dbgrid_td'>&nbsp;</td>";
            table += "<td class='dbgrid_td'><span><input type='text' name='upc[]' size='20' class='attribute_input_text' value=''></span></td>";
            for(j=0;j<items[i].length;j++){
                //table += "<td class='dbgrid_td'>";
                //table += "<span><input type='text' name='attribute"+ j +"[]' size='10' class='attribute_input_text' value='"+ names[j] +"'/></span>";
                //table += "</td>";
                table += "<td class='dbgrid_td'>";
                table += "<span><input type='hidden' name='value"+ j +"[]' class='attribute_input_text' value='"+ items[i][j] +"' /><input type='text' name='valueLabel"+ j +"[]' size='10' class='attribute_input_text' value='"+ labels[i][j] +"' readonly='readonly' /></span>";
                table += "</td>";
            }            
            //table += "<td class='dbgrid_td'><span><input type='text' name='sku[]' size='10' class='attribute_input_text' value=''></span></td>";
            table += "<td class='dbgrid_td'><span><input type='text' name='pPrice[]' size='10' class='attribute_input_text' value='"+ purchasingPricePreset +"'></span></td>";
            table += "<td class='dbgrid_td'><span><input type='text' name='cPrice[]' size='10' class='attribute_input_text' value='"+ costPricePreset +"'></span></td>";
            table += "<td class='dbgrid_td'><span><input type='text' name='mPrice[]' size='10' class='attribute_input_text' value='"+ marketingPricePreset +"'></span></td>";
            table += "<td class='dbgrid_td'><span><input type='text' name='lPrice[]' size='10' class='attribute_input_text' value='"+ listPricePreset +"'></span></td>";
            table += "<td class='dbgrid_td'><span><input type='text' name='sPrice[]' size='10' class='attribute_input_text' value='"+ salePricePreset +"'></span></td>";
            table += "<td class='dbgrid_td'><span><input type='text' name='weight[]' size='10' class='attribute_input_text' value='"+ weightPreset +"'></span></td>";
            table += "<td class='dbgrid_td'><span><input type='text' name='inventory[]' size='10' class='attribute_input_text' value='"+ inventoryPreset +"'></span></td>";
            //table += "<td class='dbgrid_td'><span><select name='place[]'><option value='2'>Local</option></select></span></td>";
            //table += "<td class='dbgrid_td'><span><select name='shippingType[]'><option value='1'>Common</option><option value='2'>Special</option><option value='3'>No Shipping</option></select></span></td>";
            //table += "<td class='dbgrid_td'><span><select name='freeShippingStatus[]'><option value='1'>Yes</option><option value='0'>No</option></select></span></td>";
            table += "<td class='dbgrid_td'><span><select name='visible[]'><option value='1'>Yes</option><option value='0'>No</option></select></span></td>";
            if(i==0){
               table += "<td class='dbgrid_td'><span><input type='radio' name='defaultItem' value='1' checked></span></td>";
            }else{
               table += "<td class='dbgrid_td'><span><input type='radio' name='defaultItem' value='1'></span></td>";
            }
            table += "</tr>";
        }
        table += '</tbody>';
        table += "</table>";
        Inventory.removeAllAttributes();//for modify items
        $("#attributeTables").empty();
        $("#attributeTables").append(table);
        $("#attributeTables").show();
        $("#initItemBtnDiv").hide();
        this.closeAttrDialog();
    },

    removeAttributes : function(){
        var attributeCheckBox = $("input[name='attributeCheckBox']");
        $(attributeCheckBox).each(function(n,obj){
            if($(obj).attr("checked")){
                value = $(obj).val();
                $("#attributeRow" + value).remove();
            }
        });
    },

    removeSelectedAttr: function(){
        var deletedItems = $("#deletedItems").val();
        var attributeCheckBox = $("input[name='attributeCheckBox']");
        $(attributeCheckBox).each(function(n,obj){
            if($(obj).attr("checked")){
                value = $(obj).val();
                if($("#productItemId" + value) && $("#productItemId" + value).val() != "" && $("#productItemId" + value).val() > 0){
                   deletedItems += $("#productItemId" + value).val() + ",";
                }
                $("#attributeRow" + value).remove();
            }
        });
        $("#deletedItems").val(deletedItems);
    },

    removeAllAttributes : function(){
        if($("#deletedItems")){
            var deletedItems = $("#deletedItems").val();
            var attributeCheckBox = $("input[name='attributeCheckBox']");
            $(attributeCheckBox).each(function(n,obj){
                value = $(obj).val();
                if($("#productItemId" + value) && $("#productItemId" + value).val() != "" && $("#productItemId" + value).val() > 0){
                    deletedItems += $("#productItemId" + value).val() + ",";
                }
                $("#attributeRow" + value).remove();
            });
            $("#deletedItems").val(deletedItems);
        }
    },

    addAttribute : function(attrCount){
        var count = $("#attributeCount").val();
        var row = "";
        row += "<tr id='attributeRow"+ count +"'>";
        row += "<td class='dbgrid_td_ckb'><input type='hidden' id='productItemId" + count + "' name='itemId[]' value='0' /><input type='checkbox' name='attributeCheckBox' value='"+ count +"' /></td>";
        row += $("#addNewItemHtml").html();
//        for(i=0;i<attrCount;i++){
//            //row += "<td class='dbgrid_td'>";
//            //row += "<span><input type='text'  name='attribute"+ i +"[]' size='10' class='attribute_input_text' value=''/></span>";
//            //row += "</td>";
//            row += "<td class='dbgrid_td'>";
//            row += "<span><input type='text'  name='value"+ i +"[]' size='10' class='attribute_input_text' value=''/></span>";
//            row += "</td>";
//        }
//        row += "<td class='dbgrid_td'><span><input type='text' name='upc[]' size='10' class='attribute_input_text' value=''/></span></td>";
//        row += "<td class='dbgrid_td'><span><input type='text' name='sku[]' size='10' class='attribute_input_text' value=''/></span></td>";
//        row += "<td class='dbgrid_td'><span><input type='text' name='pPrice[]' size='10' class='attribute_input_text' value=''/></span></td>";
//        row += "<td class='dbgrid_td'><span><input type='text' name='cPrice[]' size='10' class='attribute_input_text' value=''/></span></td>";
//        row += "<td class='dbgrid_td'><span><input type='text' name='lPrice[]' size='10' class='attribute_input_text' value=''/></span></td>";
//        row += "<td class='dbgrid_td'><span><input type='text' name='weight[]' size='10' class='attribute_input_text' value=''/></span></td>";
//        row += "<td class='dbgrid_td'><span><input type='text' name='inventory[]' size='10' class='attribute_input_text' value=''/></span></td>";
//        row += "<td class='dbgrid_td'><span><select name='place[]'><option value='1'>Local</option></select></span></td>";
//        row += "<td class='dbgrid_td'><span><select name='shippingType[]'><option value='1'>Common</option><option value='2'>Special</option><option value='3'>No Shipping</option></select></span></td>";
//        row += "<td class='dbgrid_td'><span><select name='freeShippingStatus[]'><option value='1'>Yes</option><option value='0'>No</option></select></span></td>";
//        row += "<td class='dbgrid_td'><span><select name='visible[]'><option value='1'>Yes</option><option value='0'>No</option></select></span></td>";
//        row += "<td class='dbgrid_td'><span><input type='radio' name='defaultItem' value='1'></span></td>";
        row += "</tr>";
        $("#attributeTableTbody").append(row);
        count = parseInt(count) + 1;
        $("#attributeCount").val(count);
    },

    modifyItems : function(){
        $("#init_warn_msg").show();
        Inventory.openAttrDialog();
    },

    validateProTitle : function(url){
       var value = $.trim($("#title").val());
       ValidationUtil.clearErrorMsg("title");
       if(ValidationUtil.isBlank(value)){
            ValidationUtil.showErrorMsg("title", "isEmpty");
            return false;
       }
       //validate unique
       var id = document.getElementById("id");
       if(id){
           var idValue = $("#id").val();
           if(!ValidationUtil.isUniqueByPost(url,value,idValue)){
               ValidationUtil.showErrorMsg("title", "unique");
               return false;
           }
       }else{
           if(!ValidationUtil.isUniqueByPost(url,value)){
               ValidationUtil.showErrorMsg("title", "unique");
               return false;
           }
       }
       return true;
    },

    validateProUrlTitle : function(url){
       var value = $.trim($("#urlTitle").val());
       ValidationUtil.clearErrorMsg("urlTitle");
       if(ValidationUtil.isBlank(value)){
            ValidationUtil.showErrorMsg("urlTitle", "isEmpty");
            return false;
       }
       //validate unique
       var id = document.getElementById("id");
       if(id){
           var idValue = $("#id").val();
           if(!ValidationUtil.isUniqueByPost(url,value,idValue)){
               ValidationUtil.showErrorMsg("urlTitle", "unique");
               return false;
           }
       }else{
           if(!ValidationUtil.isUniqueByPost(url,value)){
               ValidationUtil.showErrorMsg("urlTitle", "unique");
               return false;
           }
       }
       return true;
    },

    validateProSeoTitle : function(){
       var value = $.trim($("#seoTitle").val());
       ValidationUtil.clearErrorMsg("seoTitle");
       if(ValidationUtil.isBlank(value)){
            ValidationUtil.showErrorMsg("seoTitle", "isEmpty");
            return false;
       }
       return true;
    },

    validateProUpc : function(){
        var result = true;
        var upcs = $("input[name='upc[]']");
        if(upcs){
            $("form input[name='upc[]']").each(function(n,obj){
                var value = $.trim($(obj).val());
                if(ValidationUtil.isBlank(value)){
                   $(obj).css("border","1px solid red");
                   result = false;
                }else{
                   $(obj).css("border","none");
                }
            });
        }
        return result;
    },

    validateProPurchasingPrice : function(){
        var result = true;
        var prices = $("input[name='pPrice[]']");
        if(prices){
            $("form input[name='pPrice[]']").each(function(n,obj){
                var value = $.trim($(obj).val());
                if(ValidationUtil.isBlank(value) || ValidationUtil.isNumber(value)){
                   $(obj).css("border","1px solid red");
                   result = false;
                }else{
                   $(obj).css("border","none");
                }
            });
        }
        return result;
    },

    validateProCostPrice : function(){
        var result = true;
        var prices = $("input[name='cPrice[]']");
        if(prices){
            $("form input[name='cPrice[]']").each(function(n,obj){
                var value = $.trim($(obj).val());
                if(ValidationUtil.isBlank(value) || ValidationUtil.isNumber(value)){
                   $(obj).css("border","1px solid red");
                   result = false;
                }else{
                   $(obj).css("border","none");
                }
            });
        }
        return result;
    },

    validateProListPrice : function(){
        var result = true;
        var prices = $("input[name='lPrice[]']");
        if(prices){
            $("form input[name='lPrice[]']").each(function(n,obj){
                var value = $.trim($(obj).val());
                if(ValidationUtil.isBlank(value) || ValidationUtil.isNumber(value)){
                   $(obj).css("border","1px solid red");
                   result = false;
                }else{
                   $(obj).css("border","none");
                }
            });
        }
        return result;
    },

    validateProSalePrice : function(){
        var result = true;
        var prices = $("input[name='sPrice[]']");
        if(prices){
            $("form input[name='sPrice[]']").each(function(n,obj){
                var value = $.trim($(obj).val());
                if(ValidationUtil.isBlank(value) || ValidationUtil.isNumber(value)){
                   $(obj).css("border","1px solid red");
                   return result;
                }else{
                   $(obj).css("border","none");
                }
            });
        }
        return result;
    },

    validateProWeight : function(){
        var result = true;
        var weights = $("input[name='weight[]']");
        if(weights){
            $("form input[name='weight[]']").each(function(n,obj){
                var value = $.trim($(obj).val());
                if(ValidationUtil.isBlank(value) || ValidationUtil.isNumber(value)){
                   $(obj).css("border","1px solid red");
                   result = false;
                }else{
                   $(obj).css("border","none");
                }
            });
        }
        return result;
    },

    validateProInventory : function(){
        var result = true;
        var inventory = $("input[name='inventory[]']");
        if(inventory){
            $("form input[name='inventory[]']").each(function(n,obj){
                var value = $.trim($(obj).val());
                if(ValidationUtil.isBlank(value) || ValidationUtil.isNumber(value)){
                   $(obj).css("border","1px solid red");
                   result = false;
                }else{
                   $(obj).css("border","none");
                }
            });
        }
        return result;
    },

    validateProItems : function(){
        ValidationUtil.clearErrorMsg("itemError");
        var result = true;
        //if(!this.validateProUpc()){
        //    result = false;
        //}
        if(!this.validateProPurchasingPrice()){
            result = false;
        }
        if(!this.validateProCostPrice()){
            result = false;
        }
        if(!this.validateProListPrice()){
            result = false;
        }
        if(!this.validateProSalePrice()){
            result = false;
        }
        if(!this.validateProWeight()){
            result = false;
        }
        if(!this.validateProInventory()){
            result = false;
        }
        if(!result){
           ValidationUtil.showErrorMsg("itemError", "itemError");
        }
        return result;
    },

    submitProduct : function(url){
         var result = true;
         if(!this.validateProTitle(url+"/uniquetitle")){
             result = false;
         }
         if(!this.validateProUrlTitle(url+"/uniqueurltitle")){
             result = false;
         }
         if(!this.validateProSeoTitle()){
             result = false;
         }
         if(!this.validateProItems()){
             result = false;
         }
         if(!result){
             return;
         }
         var selectId = tree.getAllChecked();        
         if(selectId == ""){
             jAlert($("#errorSelectCategory").val());
             return;
         }else if(selectId == "-1"){
             jAlert($("#errorSelectRoot").val());
             return;
         }
         $("#categoryId").val(selectId);
         var defaultItems = $("input[name='defaultItem']");
         var defalutItemVal = new Array();
         var isHaveDefault = false;
         $(defaultItems).each(function(n,obj){
             if($(obj).attr("checked")){
                defalutItemVal.push("1");
                isHaveDefault = true;
             }else{
                defalutItemVal.push("0");
             }
         });
         if(!isHaveDefault){
             jAlert($("#errorDefaultItem").val());
             return;
         }
         $("#defaultItemVal").val(defalutItemVal.join());
         Common.submit();
    },

    openSearchDialog: function(baseUrl){
        var url = baseUrl + "/inventory/product/searchrelate";
        Common.showDialog({
            url : url ,
            height : 450 ,
            width : 930 ,
            dataDiv : "searchDialog"
        });
    },

    getRelate: function(data){
    	$("#productId").val(data[0].id);
        Common.closeDialog("searchDialog");
    },
    
    openAddCategoryDialog: function(baseUrl){
        var url = baseUrl + "/inventory/category/add";
        Common.showDialog({
            url : url ,
            height : 580 ,
            width : 750 ,
            dataDiv : "categoryDialog"
        });
    },

    copyProductTitle : function(){
        var title = $("#title").val();
        title = title.replace(/ /ig, "-");
        $("#urlTitle").val(title.toLowerCase());
        $("#urlTitleMsgLabel").html(title.toLowerCase());
    },

    copyProductUrlTitle : function(){
        $("#urlTitleMsgLabel").html($("#urlTitle").val());
    },

    selectMetadataSet: function(baseUrl){
        var set = $("#metadataSet").val();
        var url = baseUrl + "/inventory/product/add/set/" + set;
        Common.gotoUrl(url);
    },

    insertChildCategory: function(baseUrl){
        $("#categoryConfirmDialog").dialog("close");
        var eventId = $("#categoryEventId").val();
        var url = baseUrl + "/inventory/category/add/parentId/" + eventId;
        Common.showDialog({
            url : url ,
            height : 580 ,
            width : 750 ,
            dataDiv : "categoryDialog"
        });
    },

    editThisCategory:function(url){
            $("#categoryConfirmDialog").dialog("close");
            var eventId = $("#categoryEventId").val();
            Common.showDialog({
                url : url + "/inventory/category/edit/id/" + eventId ,
                height : 580 ,
                width : 750 ,
                dataDiv : "categoryDialog"
            });
    },
    
    //查看图片
    showItemImage : function(url, itemId, pid){
    	CommonDialog.showDialog({
            url : url + "/inventory/product/edititemimage/id/" + itemId + "/pid/" + pid ,
            height : 580 ,
            width : 950 ,
            dataDiv : "showItemImage"
        });
    },
    
    //编辑图片属性
    showImageInfo : function(url, imageId){
    	Common.showDialog({
            url : url + "/inventory/product/editimageinfo/id/" + imageId ,
            height : 180 ,
            width : 300 ,
            dataDiv : "showImageInfo"
        });
    },
    
    //删除图片//id is product_item_images table id
    deleteImage : function(url, id, itemId, pid){
    	$.ajax({
            type: 'post',
            url: url + "/inventory/product/deleteimage/id/" + id ,
            dataType: "json",
            //data: {"itemId" : itemId},
            async: false,
            success: function(){
    			//window.parent.frames['frame1'].location.reload();
    			document.location=url + "/inventory/product/editimageinfo/pid/"+pid+"/itemId/"+itemId;
            },
            error: function(){
            }
        });
    },
    
    //更改图片属性：sort_order，default_item_image
    subEditImage : function(url, itemId, pid){
    	var productId = $("#productId").val();;
    	var itemId = $("#currentUseItemId").val();;
    	var imageIdArray = Array();
        var sortArray = Array();
        var imageId = $("input[name='imageId[]']");
        var sort = $("input[name='sortOrder[]']");
        $.each(imageId, function(i, obj){
            imageIdArray[imageIdArray.length] = obj.value;
        });
        $.each(sort, function(i, obj){
        	sortArray[sortArray.length] = obj.value;
        });
        var imageIds = imageIdArray.join(",");
        var sorts = sortArray.join(",");
        var defaultImages = $("input[name='defaultImage']:checked").val();
    	$.ajax({
            type: 'post',
            url: url + "/inventory/product/editimageattribute" ,
            dataType: "json",
            data: {"itemId" : itemId , "imageIds" : imageIds , "sorts" : sorts , "defaultImages" : defaultImages},
            async: false,
            success: function(){
            	document.location=url + "/inventory/product/editimageinfo/pid/"+productId+"/itemId/"+itemId;
            },
            error: function(){
                
            }
        });
    },
    
    //确认用户设置了default_item_image
    checkDefaultImage : function(url, itemId){
    	var result;
    	$.ajax({
            type: 'post',
            url: url + "/inventory/product/issetdefaultimage/itemId/" + itemId ,
            dataType: "json",
            //data: {"isDefaultImage" : isDefaultImage , "sortOrder" : sortOrder , "itemId" : itemId},
            async: false,
            success: function(isSet){
    			if(isSet.isDefaultImage){
    				result = true;
    			}else{
    				result = false;
    			}
            },
            error: function(){
            	result = false;
            }
        });
        return result;
    },
    
    //鼠标经过改变CSS样式
    addCSS : function(id){
    	$("#"+id).addClass("image_change");
    },
    delCSS : function(id){
    	$("#"+id).removeClass("image_change");
    },
    
    //提交表单
    subUploadImage : function(){
    	var url = $("#uploadUrl").val();
    	var productId = $("#uploadProductId").val();
    	var itemId = $("#uploadItemId").val();
		$('#imageForm').submit();
    },
    
    closeWindow : function(){
    	window.close();
    },
    
    //第一张图片选好了默认图，则将其他图片设置成非默认图片
    isDefaultImage : function(currentNumber){
    	var isDefault = $('#defaultImage_'+currentNumber).val();
    	if(isDefault == 1){
    		for(var i = 0; i < 10; i++){
    			if(i != currentNumber){
    				$("#defaultImage_"+i).attr("value","0");
    			}
    		}
    	}
    	
    },
    
    //第一张图片选好了显示顺序1后,其他图片显示顺序自动为2，3，4等
    setImageSort : function(currentNumber){
    	if(currentNumber == 0){
    		var currentSort;
    		if(isNaN($('#sortOrder_0').val())){
    			currentSort = 1;
    		}else{
    			currentSort = Number($('#sortOrder_0').val());
    		}
    		for(var i = 1; i < 10; i++){
    			currentSort = currentSort + 1;
    			$('#sortOrder_'+i).val(currentSort);
    		}
    	}
    }
    
}



var CommonDialog = {
		
	showDialog: function(config){
		var dialogId = config.dataDiv;
		var data = "";
		if(config.data){
			data = config.data;
		}
		var url = config.url;
		var height = config.height;
		var width = config.width;
		//init dialog
		$("#" + dialogId).dialog({
			modal: true ,
			height: height ,
			autoOpen: false,
			width: width,
			resizable: false,
			overlay: {
			opacity: 0.6,
			background: "#555555"
		},
		beforeclose: function(event, ui) { 
			var url = $("#urlPath").val();
			var itemId = $("#editImageItemId").val();
			//var isEmptyImageInfo = $("#isEmptyImageInfo").val();
			var errorInfoDefaultImage = $("#errorInfoDefaultImage").val();
			//if(isEmptyImageInfo == 0){//如果有图片信息
				var isClose = Inventory.checkDefaultImage(url, itemId);//判断是否设置了默认图片
				if(isClose){
					$("#" + dialogId).dialog( 'destroy' );
					return true;
				}else{
					jAlert(errorInfoDefaultImage);
					return false;
				}
			//}
		},
		close: function(event, ui) {
			$("#" + dialogId).dialog( 'destroy' );
		}
		});
		//get html content from server
		$.ajax({
			type:"POST",
			async:false,
			url:url,
			data: data,
			dataType:"Html",
			success:function(responseText){
			$("#" + dialogId).empty();
			$("#" + dialogId).html(responseText);
			$("#" + dialogId).dialog("open");
		}
		});
	}
	
}



